import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    const { code, msg, data } = response.data
    if (code === 200) {
      return { success: true, data, message: msg }
    } else if (code === 401) {
      // 401未授权，清空用户登录状态并跳转到登录页
      import('@/stores/user').then(({ useUserStore }) => {
        import('@/router').then(({ default: router }) => {
          const userStore = useUserStore()
          userStore.logout()
          router.push('/login')
        })
      })
      
      return { success: false, message: msg || '登录已过期，请重新登录' }
    } else {
      return { success: false, message: msg || '请求失败' }
    }
  },
  error => {
    let message = '网络错误'
    if (error.response) {
      message = error.response.data?.msg || `请求失败 ${error.response.status}`
    }
    return { success: false, message }
  }
)

export default api